package textconvert;

import java.util.Vector;

/**
 * xxxxxx<%=$%>hhhhhhhh<%=$%>cccccc<%$%>eeee
 * {xxxxxx<%=$%>hhhhhhhh<%=$%>cccccc} {<%$%>eeee}
 * @author Bing
 * @copyright (c)
 *
 */
public class RulePattern {
	private byte[] ruleText;
	private Vector rules = new Vector();
	private int currRule = 0;
	
	public RulePattern(byte[] ruleText){
		this.ruleText = new byte[ruleText.length];
		System.arraycopy(ruleText, 0, this.ruleText, 0, ruleText.length);
		parserRuleText(this.ruleText);
	}
	
	private void parserRuleText(byte[] ruleText){		
		ConstByteArray rr = new ConstByteArray(ruleText, 0, ruleText.length);
		int p0 = 0;
		int p1 = 0;
		for(int i=0; ;){
			if( (p0 = rr.indexOf(FormatRule.TAG_S, i)) == -1 ) 
				break;
			if(p0 > i){
				rules.addElement(new FormatRule(rr.getSubArray(i, p0-i)));
			}
			if( (p1 = rr.indexOf(FormatRule.TAG_E, p0 + FormatRule.TAG_S.length)) != -1 ) 
				break;
			if(rr.byteAt(p0 + FormatRule.TAG_S.length)=='='){
				FormatRule prev = this.rules.isEmpty()? null : (FormatRule)this.rules.elementAt(this.rules.size()-1);
				if(prev!=null)
					prev.addNext(new FormatRule(rr.getSubArray(p0, p1+FormatRule.TAG_E.length-p0)));
			}else
				rules.addElement(new FormatRule(rr.getSubArray(p0, p1+FormatRule.TAG_E.length-p0)));				
			i = p1 + FormatRule.TAG_E.length;
		}			
	}
	
	public FormatRule getRule(int i){
		if(i<rules.size())
			return (FormatRule)rules.elementAt(i);
		return null;
	}

	public FormatRule next(){
		return getRule(currRule++);
	}
	
	public FormatRule peekNext(){
		return getRule(currRule);
	}
	
	public int size(){
		return rules.size();
	}
}
